#include "../util/types.h"
#include "../util/x86.c"
#include "../util/elf.h"
#include "bootMain.h"

extern void myPrintfDebug (uint, uchar);

#define SECTSIZE  512

void readseg(uint, uint, uint);

typedef void (*entryTy)();

void bootMain(void)
{
  elfHeaderPtr elf;
  progHeaderPtr ph, eph;
  entryTy entry;

  elf = (elfHeaderPtr)0x10000;  // scratch space

  // Read 1st page off disk
  readseg((uint)elf, SECTSIZE*8, 0);

  // Is this an ELF executable?
  if(elf->magic != ELF_MAGIC)
    goto bad;

  // Load each program segment (ignores ph flags).
  ph = (progHeaderPtr)((uchar*)elf + elf->phoff);
  eph = ph + elf->phnum;
  for(; ph < eph; ph++)
  {
    readseg(ph->va, ph->memsz, ph->offset);
  }
  
  // debug util
//  myPrintfDebug (0, 'X');

  // Call the entry point from the ELF header.
  // Does not return!
  entry = (entryTy)(elf->entry & 0xFFFFFF);
  //  entry = (void (*)(void))0x100000;
  entry();

  // debug util
  //myPrintfDebug (1602, 'Z');

bad:
  //myPrintfDebug (0, 'd');
  //myPrintfDebug (2, 'i');
//  myPrintfDebug (4, 'e');
  for(;;)
    ;
}

inline void waitDisk(void)
{
  // Wait for disk ready.
  while((inb(0x1F7) & 0xC0) != 0x40)
    ;
}

// Read a single sector at offset into dst.
void readSector (void *dst, uint offset)
{
  // Issue command.
  waitDisk();
  outb(0x1F2, 1);   // count = 1
  outb(0x1F3, offset);
  outb(0x1F4, offset >> 8);
  outb(0x1F5, offset >> 16);
  outb(0x1F6, (offset >> 24) | 0xE0);
  outb(0x1F7, 0x20);  // cmd 0x20 - read sectors

  // Read data.
  waitDisk();
  insl(0x1F0, dst, SECTSIZE/4);
}

// Read 'count' bytes at 'offset' from kernel into virtual address 'va'.
// Might copy more than asked.
void readseg(uint va, uint count, uint offset)
{
  uint eva;

  va &= 0xFFFFFF;
  eva = va + count;

  // Round down to sector boundary.
  va &= ~(SECTSIZE - 1);

  // Translate from bytes to sectors; kernel starts at sector 1.
  offset = (offset / SECTSIZE) + 1;

  // If this is too slow, we could read lots of sectors at a time.
  // We'd write more to memory than asked, but it doesn't matter --
  // we load in increasing order.
  for(; va < eva; va += SECTSIZE, offset++)
    readSector ((uchar*)va, offset);
}
